development/superseded functions/query_layer_ms.R

#' Query Map Server Layer
#'
#' Download feature layer from a Map Server
#'
#' @param host url for the ArcGIS Server host e.g 'https://services.arcgis.com'
#' @param instance a string defining the ArcGIS Server instance. The default is "arcgis"
#' @param folder a string defining the folder name
#' @param service_name a string defining the name of the service name
#' @param layer_id an integar defining the layer id (starting at 0)
#' @param my_token an access token acquired via \code{get_token}
#' @param query a named vector of parameters to include in the query
#' @param bounding_box an optional bounding box (generated by sf::st_bbox()) to perform a spatial intersects
#' @param crs the output crs, defaulting to 4326
#'
#' @return an sf object
#' @export query_ms_layer
#'
#' @import httr
#' @import sf
#' @importFrom magrittr %>%
query_layer_ms <- function(host,
                           instance = "arcgis",
                           folder,
                           service_name,
                           layer_id = 0,
                           crs = 4326,
                           bounding_box = NULL,
                           my_token = NULL,
                           query = NULL) {
  endpoint <-
    map_server_endpoint(host,
                        instance,
                        folder,
                        service_name,
                        layer_id)

  # If a bounding box has been specified then generate the spatial query and combine with the query parameters
  if (!is.null(bounding_box)) {
    query <- c(query, spatial_query_to_list(bbox = bounding_box))
  }
  # Define a named vecotr of default query parameters for returning spatial data
  default_parameters <- c(returnIdsOnly = "false",
                          # Get all features with sql query 1 = 1
                          where = "1=1",
                          outFields = "*",
                          returnCountOnly = "false",
                          f = "json",
                          token = NULL,
                          # Assert that the data is lat lon if writing to geojson
                          outSR = 4326)

  default_parameters <- default_parameters[!(names(default_parameters) %in% names(query))]
  query <- c(default_parameters, query)

  # Generate the query string
  query_string <- query_string(query = query, my_token = my_token)

  query_url <- paste0(endpoint, "/query", query_string)
  message(paste0("Requesting data:\n", query_url))
  print(query_url)
  data <- get_geojson(query_url)


  # If the specified crs is not 4326 (the current crs) then transform the data
  if (crs != 4326) {
    data <- data %>% sf::st_transform(crs = crs)
  }

  return(data)
}
MatthewJWhittle/getarc documentation built on April 22, 2023, 12:16 p.m.